package be.pollsg1.repository.impl;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import be.pollsg1.repositories.BaseEntityRepository;


@SuppressWarnings("unchecked")
public class GenericRepositoryJpa<T,ID> implements BaseEntityRepository<T,ID> {
     
	@PersistenceContext(unitName="PollsG1PU")
	protected EntityManager entityManager;
	 private Class<T> entityClass;
	// private Class<ID> privateKeyClass;
	 
	public GenericRepositoryJpa() {
		this.entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	  //  this.privateKeyClass = (Class<ID>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
		   
	}

	@Override
	public T insert(T o) {
		entityManager.persist(o);
		return o;
	}

	@Override
	public T update(T o) {
		o=entityManager.merge(o);
	  return o;	
	}

	@Override
	public T findById(Long id) {
	
		 Object obj = entityManager.find(entityClass, id);
	        if (obj == null)
	            return null;
	        return (T) obj;
	}

	@Override
	public void delete(T o) {
		o =entityManager.merge(o);
		entityManager.remove(o);
		
	}

	@Override
	public List<T> findAll() {
		List<T> Ts = new ArrayList<>();
		TypedQuery<T> query = entityManager.createNamedQuery(entityClass.getSimpleName()+".findAll", entityClass);
		Ts = query.getResultList();

		return Ts;
	}

	 
}
